package com.example.campuslink.viewModel.ai

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.ai.AiTable
import com.example.campuslink.commen.db.userInfo.UserInfoTable
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpKey
import com.example.campuslink.commen.tools.putExtraKey
import com.example.campuslink.model.DeepSeekTalkData
import com.example.campuslink.ui.activity.ai.AiDetailActivity
import com.example.campuslink.ui.activity.ai.AiHistoryActivity
import com.example.campuslink.viewModel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.HttpException
import java.io.IOException
import java.net.SocketTimeoutException

class InquiriesViewModel : BaseViewModel() {
    private val _userInfo = MutableLiveData<UserInfoTable>()
    val userInfo get() = _userInfo


    fun getUserInfoTable() {
        viewModelScope.launch(Dispatchers.IO) {
            _userInfo.postValue(
                userInfoDao?.getUserInfoByUserNumber(
                    Sp.getString(
                        context ?: return@launch,
                        SpKey.USER_NUMBER.key ?: "",
                        ""
                    ) ?: ""
                )
            )
        }
    }

    fun jumpToHistory() {
        startActivity(Intent(), targetClass = AiHistoryActivity::class.java)
    }

    fun jumpToDetail(deepSeekTalkData: DeepSeekTalkData) {
        startActivity(Intent().apply {
            putExtra(putExtraKey.AI_TALK_DATA.key ?: "", deepSeekTalkData)
        }, targetClass = AiDetailActivity::class.java)
    }

    fun handleError(e: Exception): String {
        var eToast = ""
        val errorMessage = when (e) {
            is HttpException -> when (e.code()) {
                401 -> eToast = "认证失败，请检查API KEY"
                429 -> eToast = "请求过于频繁，请稍后再试"
                500 -> eToast = "服务器内部错误"
                else -> eToast = "服务器繁忙 (${e.code()})"
            }

            is SocketTimeoutException -> eToast = "请求超时，请检查网络"
            is IOException -> eToast = "网络连接错误：${e.message}"
            else -> eToast = "未知错误：${e.localizedMessage}"
        }
        return eToast
    }

    private val _historyList = MutableLiveData<List<DeepSeekTalkData>>()
    val historyList get() = _historyList


    fun deleteHistoryList(deepSeekTalkData: DeepSeekTalkData) {
        viewModelScope.launch(Dispatchers.IO) {
            val aiTable = aiDao.getAiTable(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
            )
            aiTable?.aiTalkData?.remove(deepSeekTalkData)
            aiDao.updateAiTable(aiTable ?: return@launch)
            _historyList.postValue(aiTable.aiTalkData ?: mutableListOf())
        }
    }


    fun getAiHistoryList() {
        viewModelScope.launch(Dispatchers.IO) {
            val aiTable = aiDao.getAiTable(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
            )
            _historyList.postValue(aiTable?.aiTalkData ?: mutableListOf())
        }
    }

    fun addAiHistory(deepSeekTalkData: DeepSeekTalkData) {
        viewModelScope.launch(Dispatchers.IO) {
            var aiTable = aiDao.getAiTable(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
            )
            if (aiTable == null) {
                val tempAiTable = AiTable()
                tempAiTable.userNumber = Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
                tempAiTable.newAddCount = 0
                tempAiTable.id = aiDao.getMaxId() ?: 0 + 1
                tempAiTable.aiTalkData = mutableListOf()
                aiDao.insertAiTable(tempAiTable)
            }
            aiTable = aiDao.getAiTable(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: ""
            )
            aiTable?.aiTalkData?.add(deepSeekTalkData)
            aiDao.updateAiTable(aiTable ?: return@launch)
        }
    }
}